import React, { useState, useEffect } from 'react'
import { Breadcrumb, Card, Table, Button, Col, Row, Input, Tree, Modal, Form, Popconfirm, message } from 'antd'
import { getrole, deleterole, updaterole, addrole } from '../../../../api/index'
import './role.css'

const layout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 16 },
};

const Role = () => {
    const [roleList, setroleList] = useState([])
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isEdit, setIsEdit] = useState(false)
    const [form] = Form.useForm();
    const [record, setRecord] = useState({})

    const [expandedKeys, setExpandedKeys] = useState([]);
    const [checkedKeys, setCheckedKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);
    const [treeData, setTreeData] = useState([])
    const onExpand = (expandedKeysValue) => {
        console.log('onExpand', expandedKeysValue); // if not set autoExpandParent to false, if children expanded, parent can not collapse.
        // or, you can remove all expanded children keys.

        setExpandedKeys(expandedKeysValue);
        setAutoExpandParent(false);
    };

    const onCheck = (checkedKeysValue) => {
        console.log('onCheck', checkedKeysValue);
        setCheckedKeys(checkedKeysValue);
    };

    const onSelect = (selectedKeysValue, info) => {
        console.log('onSelect', info);
        setSelectedKeys(selectedKeysValue);
    };


    useEffect(() => {
        getroleList()
    }, [])
    const columns = [
        {
            title: 'id',
            dataIndex: 'key',
        },
        {
            title: '角色名',
            dataIndex: 'name',
        }, {
            title: '操作',
            dataIndex: 'action',
            render: (text, record) => {
                return <div>
                    <Button type='primary' onClick={() => changeAuth(record)}>菜单权限</Button>
                    <Popconfirm
                        title="确定删除吗"
                        onConfirm={() => confirm(record)}
                        onCancel={cancel}
                        okText="Yes"
                        cancelText="No"
                    >
                        <Button type='error'>删除</Button>
                    </Popconfirm>
                </div>
            }
        }
    ];
    //获取角色列表
    const getroleList = async () => {
        const { data: res } = await getrole()
        if (res.code === 0) {
            message.success(res.msg)
            setroleList([...res.data])
        }
    }
    //点击确认
    const handleOk = () => {
        if (isEdit) {
            editItem()
        } else {
            addItem()
        }
        setIsModalVisible(false);
    };
    //添加
    const addItem = async () => {
        let formItem = form.getFieldValue()
        formItem.treeData = [
            {
                title: '系统',
                key: 'system',
                children: [
                    {
                        title: '模块管理',
                        key: 'modles',
                        children: [
                            {
                                title: '地区管理',
                                key: 'area',
                            },
                            {
                                title: '学校管理',
                                key: 'school',
                            },
                            {
                                title: '地铁管理',
                                key: 'subway',
                            },
                        ],
                    },
                    {
                        title: '人员权限',
                        key: 'auth',
                        children: [
                            {
                                title: '人员管理',
                                key: 'authman',
                            },
                            {
                                title: '角色管理',
                                key: 'role',
                            },
                        ],
                    },
                ],
            },
            {
                title: '楼盘',
                key: 'houses',
                children: [
                    {
                        title: '楼盘管理',
                        key: 'houseman',
                        children: [
                            {
                                title: '楼盘列表',
                                key: 'houselist'
                            }
                        ]
                    },
                    {
                        title: '开发商管理',
                        key: 'developers',
                    },
                ],
            },
            {
                title: '二手/租房',
                key: 'rent',
                children: [
                    {
                        title: '小区管理',
                        key: 'community',
                    },
                    {
                        title: '二手房管理',
                        key: 'second',
                    },
                    {
                        title: '出租房',
                        key: 'renthouse'
                    }
                ]
            },
        ]
        formItem.expandedKeys = ['system', 'modles', 'auth', 'houses', 'rent']
        formItem.checkedKeys = []
        formItem.selectedKeys = []
        formItem.key = Math.random().toString().slice(2, 5) + '.' + Math.random().toString().slice(2, 5) + '.' + Math.random().toString().slice(2, 4) + '.' + Math.random().toString().slice(2, 5)
        const { data: res } = await addrole({ ...formItem })
        if (res.code === 0) {
            message.success(res.msg)
            setroleList([...res.data])
        }
    }
    //编辑内容 
    const editItem = async () => {
        record.checkedKeys = [...checkedKeys]
        record.selectedKeys = [...selectedKeys]
        const { data: res } = await updaterole(record)
        setroleList([...res.data])
        message.success('修改成功')
    }
    //修改权限
    const changeAuth = (record) => {
        setIsModalVisible(true);
        setIsEdit(true);
        setTreeData([...record.treeData])
        setExpandedKeys([...record.expandedKeys])
        setCheckedKeys([...record.checkedKeys])
        setRecord({ ...record })
    }
    //点击取消
    const handleCancel = () => {
        setIsModalVisible(false);
    };
    //确认删除
    const confirm = (record) => {
        deleteItem(record)
        message.success('删除成功');
    }
    //取消删除
    const cancel = (e) => {
        message.error('取消成功');
    }
    //删除
    const deleteItem = async (record) => {
        const { data: res } = await deleterole({ id: record.key })
        setroleList([...res.data])
    }
    return <div className="role">
        <Card>
            <Breadcrumb>
                <Breadcrumb.Item>
                    <a href="/home">首页</a>
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                    <a href="/home/role">系统</a>
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                    <a href="/home/role">权限管理</a>
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                    <a href="/home/role">角色管理</a>
                </Breadcrumb.Item>
            </Breadcrumb>
        </Card>
        <Row gutter={16}>
            <Col className="gutter-row" span={4}>
                <Button type='primary' style={{ width: '100%', margin: '10px 0' }} onClick={() => {
                    form.setFieldsValue({ name: '', phone: '', role: '' });
                    setIsModalVisible(true);
                    setIsEdit(false);
                }}>添加</Button>
            </Col>
        </Row>
        <Card style={{ width: '100%', height: '100%' }}>
            <Table
                columns={columns}
                dataSource={roleList}
                pagination={{
                    defaultPageSize: 5,
                    defaultCurrent: 1
                }}
            />
        </Card>
        <Modal title={isEdit ? "编辑内容" : "添加信息"} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
            {isEdit ? <Tree
                checkable
                onExpand={onExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                onCheck={onCheck}
                checkedKeys={checkedKeys}
                onSelect={onSelect}
                selectedKeys={selectedKeys}
                treeData={treeData}
            /> : <Form
                {...layout}
                form={form}
                name="basic"
                initialValues={{ remember: true }}
            >
                <Form.Item
                    label="角色名称"
                    name="name"
                    rules={[{ required: true, message: '请输入角色名称' }]}
                >
                    <Input />
                </Form.Item>
            </Form>
            }
        </Modal>
    </div>
}
export default Role
